<template>
  <div class="addLandPage">
    <!-- <div class="back" @click="back()"><i class="el-icon-back"></i>返回</div> -->
    <div class="backFont"><el-button icon="el-icon-arrow-left" @click="back()">返回</el-button></div>
    <el-form
      :model="Form"
      :rules="rules"
      ref="mainForm"
      label-width="120px"
      class="addForm errorForm"
    >
      <el-form-item prop="geoInfo" class="addMapInForm noRequire" label="*地块真实位置：">
        <div v-if="!Form.geoInfo">
          <el-button
            size="small"
            @click="isDel = true, dialogVisible = true"
            ref="mapData"
            class="openMapBtn"
            type="primary"
          >
            <div class="openFlex"><img src="@/assets/iconImage/outline.png" /><span>绘制地块真实轮廓</span></div>
          </el-button>
          <div class="text">
            绘制地块轮廓有助于让消费者知晓农产品来源于哪个真实地块，可提升消费者的信任度 绘制轮廓后可自动计算地块面积
          </div>
        </div>
        <div class="landAddress" v-else>
          <landMap
            v-if="!dialogVisible"
            class="landMap"
            :landDetailData="Form"
            ref="landMap"
          ></landMap>
          <div class="landEdit">
            <div class="editGreen" @click="isDel = false, dialogVisible = true">
              <i class="el-icon-edit"></i>
              <div>修改</div>
            </div>
            <div class="editBlack" @click="isDel = true, Form.geoInfo = ''">
              <i class="el-icon-delete"></i>
              <div>删除</div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item class="noRequire" prop="landName" label="*地块名称：">
        <el-input placeholder="例如：一号地块" v-model="Form.landName" class="landName"></el-input>
      </el-form-item>
      <el-form-item class="noRequire" prop="landType" label="*地块类型：">
        <!-- <el-select
          v-model="Form.landType"
          class="landName"
          placeholder="请选择"
        >
          <el-option
            v-for="item in landTypes"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select> -->
        <el-button
          class="typeBtn"
          :class="Form.landType === item.code && 'checkBoxAll'"
          @click="Form.landType = item.code"
          v-for="item in landTypes"
          :key="item.id"
        >
          {{ item.name }}
        </el-button>
      </el-form-item>
      <el-form-item class="noRequire" label="*地块面积：" prop="landArea">
        <el-input :min="0" type="number" placeholder="请输入地块面积" v-model="Form.landArea" class="landName widthSuffix">
          <template #suffix>
            <div class="suffixText">亩</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="noRequire" prop="responsiblePerson" label="*负责人：">
        <el-select
          v-model="Form.responsiblePerson"
          class="landName"
          placeholder="请选择"
          @change="onSelectChange"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="noRequire" label="*负责人手机号：" prop="phone">
        <el-input  placeholder="请输入负责人手机号" v-model="Form.phone" class="landName"></el-input>
      </el-form-item>
      <el-form-item class="noRequire" label="*地块地址" prop="address">
        <el-input placeholder="地址栏不能为空" v-model="Form.address" class="landName"></el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-button
          type="primary"
          class="submitBtn"
          @click="submitForm('dynamicValidateForm')"
          >完 成</el-button
        >
      </el-form-item> -->
    </el-form>
    <div class="submitBottom">
      <el-button
        size="small"
        class="editBtn editBtnNone"
        @click="back(1)"
        >取消</el-button
      >
      <el-button
        class="editBtn"
        type="primary"
        size="small"
        @click="submitForm('mainForm')"
        >确定</el-button
      >
    </div>
    <!-- 弹窗 -->
    <el-dialog class="areaDialog" v-if="dialogVisible" :close-on-click-modal="false" :visible.sync="dialogVisible" width="1200px" :boolean="true">
      <areaMap
        ref="areaMap"
        @areaData="getAreaData"
        @dataList="dataList"
        :isDel="isDel"
        :geoInfo="Form.geoInfo"
        :landList="landList"
      ></areaMap>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="mapAddBtn()">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
// import titBox from '@/components/titBox'
import areaMap from '@/views/mapAdd/components/map.vue'
import { AddlandData, getUserListApi, getMaplandApi, UpdatelandData } from '@/api/landAdd'
import { getSysSonDictListApi } from '@/api/dict'
import landMap from '@/views/agriLandDetail/components/map.vue'

export default {
  name: 'MeilinPCIndex',
  components: {
    // titBox,
    landMap,
    areaMap
  },
  data () {
    return {
      map: {},
      mapShow: false,
      longitude: 120.524224,
      latitude: 30.184564,
      // showMap: false, //
      dialogVisible: false,
      // baseId 农场Id
      // landArea 地块面积
      // landCenter 地块中心点
      // landLatLng 圈地经纬度
      // landName 地块名称
      // landType 地块类型
      // landZoom 地块缩放值
      Form: {
        geoInfo: '',
        baseId: 1,
        landName: '',
        landType: '',
        phone: null,
        color: '#49cc90, #1f64c1'
      },
      rules: {
        // mapData: [
        //   { required: true, message: '请输入用户名', trigger: 'blur' },
        //   { validator: this.validateMapData, trigger: 'blur' }
        // ]，
        geoInfo: [{ required: true, message: '请选择地块真实位置', trigger: 'blur' }],
        landName: [
          { required: true, message: '请输入地块名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        landType: [
          { required: true, message: '请选择地块类型', trigger: 'blur' }
        ],
        landArea: [
          { required: true, message: '请输入地块面积', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('地块面积必须>0'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        responsiblePerson: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入负责人手机号', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1[1-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地块地址', trigger: 'blur' }
        ]
      },
      mapData: {}, // 合并到Form表单的数据
      userList: [], // 人员列表
      landTypes: [], // 地块类型
      baseId: 1,
      isDel: false
    }
  },

  mounted () {
    this.baseId = this.$store.getters.userInfo.baseId
    this.Form.baseId = this.$store.getters.userInfo.baseId
    this.getUserList(this.baseId)
    this.getMapland(this.baseId)
    this.getSysSonDictList()
    this.getAgrByLandIdData()
  },

  methods: {
    // 获取地块单个信息数据
    getAgrByLandIdData () {
      if (!this.$route.query.landId) {
        return
      }
      getMaplandApi(this.baseId, this.$route.query.landId).then(res => {
        this.$set(this, 'Form', res.data[0])
        this.landTypes.map(async item => {
          if (item.name === res.data[0].landType) {
            this.Form.landType = item.code
          }
        })
      })
    },
    // map组建子传父 传递圈地数据
    getAreaData (e) {
      if (
        Object.keys(this.mapData).length >= 0 &&
        Object.keys(e).length !== 1
      ) {
        this.Form.geoInfo = JSON.stringify(e.currentLnglats)// 地块经纬度
        this.Form.landArea = parseFloat((e.currentArea * 0.0015).toFixed(2))// 地块面积
        this.mapData.geoCenter = JSON.stringify(e.target.Eo)// 中心经纬度
        this.mapData.geoZoom = e.currentPolygon.KE.fW// 缩放度
        this.Form.address = e.landInfo
        this.$message.success('操作成功')
      }
      if (e.landInfo === null) {
        this.Form.address = e.landInfo
      }
    },
    //  获取地块信息
    dataList (e) {
      this.Form.geoInfo = e.polygonSubmit
      this.Form.landArea = e.area
      this.mapData.geoCenter = e.polygonCenter
      this.mapData.geoZoom = e.zoom
      this.Form.address = e.address
      this.Form = Object.assign({}, this.Form, this.mapData)
      this.dialogVisible = false
    },
    // handleAddPoint () {
    //   const T = window.T
    //   console.log(T)
    //   this.map.clearOverLays() // 清空原来的标注点
    //   const point = new T.LngLat(
    //     (this.longitude -= 0.01),
    //     (this.latitude -= 0.01)
    //   )
    //   const marker = new T.Marker(point)
    //   this.map.addOverLay(marker) // 添加标注点
    //   // 点击标注点事件，添加信息窗口
    //   const markerInfoWin = new T.InfoWindow('信息窗口')
    //   marker.addEventListener('click', function () {
    //     marker.openInfoWindow(markerInfoWin)
    //   })
    // },
    // 表单提交
    async submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.Form.geoZoom = this.Form.geoZoom.toString()
          this.Form.phone = Number(this.Form.phone)
          let res = null
          if (this.$route.query.landId) {
            res = await UpdatelandData(this.Form)
          } else {
            res = await AddlandData(this.Form)
          }
          if (res.code === 200) {
            this.$message.success('添加地块成功')
            this.$router.go(-1)
          } else {
            this.$message.error('添加地块失败')
          }
        }
      })
    },
    // 地图弹窗数据校验
    validateMapFromData () {
      console.log(this.mapData)
      if (Object.keys(this.mapData).length === 0) {
        console.log('数据为空')
        return false // 数据为空，校验失败
      }
      return true // 数据不为空，校验通过
    },
    // 弹窗确认
    mapAddBtn () {
      this.$refs.areaMap.getAreaData()
      // if (Object.keys(this.mapData).length > 0) {
      //   this.dialogVisible = false
      //   this.Form = Object.assign({}, this.Form, this.mapData)
      // } else {
      //   this.$message.error('请绘制地块')
      // }
    },
    // 弹窗取消
    closeDialog () {
      this.$message('绘制已取消')
      this.mapData = {}
      this.Form.address = null
      this.dialogVisible = false
    },

    // 返回
    back (type) {
      if (type) {
        this.$alert(
          'Tips：返回后该地块相关信息（地块名称、地块类型、地块面积、负责人等）都将会被删除）',
          '确定返回地块管理吗？',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            customClass: 'alertClass',
            showCancelButton: true,
            closeOnClickModal: false,
            showClose: false
          }).then(async () => {
          this.$router.go(-1)
        })
          .catch(action => {
          })
        return
      }
      this.$router.go(-1)
    },
    // 地块列表，添加时回显到地图上
    async getMapland (baseId) {
      const res = await getMaplandApi(baseId)
      this.landList = res.data
    },
    // 查询用户信息表
    async getUserList (baseId) {
      const res = await getUserListApi(baseId)
      // console.log(res)
      this.userList = res.data
    },
    // 字典地块类型
    async getSysSonDictList () {
      const res = await getSysSonDictListApi('DKLX')
      console.log(res.data)
      this.landTypes = res.data
    },
    // 下拉事件 更具userId 匹配对应的phone给到Form.phone
    onSelectChange (value) {
      const userInfo = this.userList.filter((item) => item.userId === value)
      // console.log(userInfo)
      this.Form.phone = userInfo[0].phone
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep .areaDialog {
  .el-dialog__body {
    padding-top: 0
  }
  .el-dialog__headerbtn {
    top: 14px;
    font-size: 22px;
    color: #000;
    z-index: 999
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__title {
    border-left: none;
    font-size: 0;
  }
}
.addLandPage {
  height: 100%;
  background: #ffffff;
  // border-radius: 20px 20px 20px 20px;
  padding-top: 1vh;
  .back {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 24px;
    position: absolute;
    top: 1.5625vw * 0.834;
    left: 1.5625vw * 0.834;
    color: #666666;
    line-height: 0px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    cursor: pointer;
  }
}
//圈地的form
.addMapInForm {
  // margin-bottom: 6.25vw * 0.834;
  .text {
    width: 520px;
    font-weight: 400;
    color: #F76560;
    text-align: left;
    margin-top: 1vh;
    line-height: 1.5
  }
}
.openMapBtn {
  background: #00C586;
  font-size: 0.9vw;
  border-radius: 2px;
  .openFlex {
    display: flex;
    align-items: center;
    img {
      width: 1.1vw;
      margin-right: 0.3vw
    }
  }
  // line-height:3.125vw *0.834 ;
}
.addForm {
  // width: 750px;
  margin-top:  3vh
  // margin: 0 auto;
}
//所有的input输入框，懒着改了
.landName {
  width: 300px;
}
.landMap {
  width: 300px !important;
  height: 18vh !important;
  border-radius: 3px;
}
.submitBtn {
  width: 380px;
  height: 60px;
  background: #19b560;
  border-radius: 12px 12px 12px 12px;
  font-size: 20px;
}
::v-deep .el-dialog {
  margin-top: 6vh !important;
}
.landAddress {
  display: flex;
  align-items: flex-start;
  .landEdit {
    margin-left: 10px;
    box-shadow: 0px 4px 16px 0px rgba(0,0,0,0.08);
    > div {
      width: 42px;
      text-align: center;
      display: flex;
      align-items: center;
      flex-direction: column;
      padding: 12px 0 8px 0;
      > div {
        line-height: 2;
      }
    }
    i {
      font-size: 18px;
    }
    .editGreen {
      border-top-left-radius: 4px;
      border-top-right-radius: 4px;
      color: #fff;
      background: #00C586;
    }
    .editBlack {
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
      color: #333333
    }
  }
}
</style>
